import React, { createContext, useState } from 'react';
import {useHistory} from 'react-router-dom';

export const AuthContext = createContext({
    checkSession: () => {},
    register: () => {},
    login: () => {},
    logout: () => {}
});

export const AuthProvider = ({children}) => {

  const history = useHistory();

  const checkSession = () => {
    return localStorage.getItem('token');
  }
  
  const register = async (mail, pass) => {

    const fetchSpecs = {
      method: 'post',
      body: JSON.stringify({mail, pass}),
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }

    const resp = await window.fetch('/register', fetchSpecs);
    
    if (resp.ok) {
      history.push('login');
    }

    const data = await resp.json();
    return data;
  }

  const login = async (mail, pass) => {

    const fetchSpecs = {
      method: 'post',
      body: JSON.stringify({mail, pass}),
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }

    try {

      const resp = await window.fetch('/login', fetchSpecs);

      const data = await resp.json();

      if (data.token) {
        localStorage.setItem('token', data.token);
        history.push('home');
      }
    
      return resp;

    } catch (err) {
      console.warn(err);
    }
  }

  const logout = () => {
    localStorage.removeItem('token');
  }

  return <AuthContext.Provider value={{login, logout, register, checkSession}}>
    {children}
  </AuthContext.Provider>
}